package com.jar.netty_demo.NIO.groupchat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;

public class ClientChat {
    private final String HOST = "127.0.0.1";
    private final int PORT = 6667;
    private Selector selector;
    private SocketChannel socketChannel;
    private String userName;

    /**
     * 初始化
     *
     * @throws IOException
     */
    public ClientChat() {
        try {
            selector = Selector.open();
            socketChannel = SocketChannel.open(new InetSocketAddress(HOST, PORT));
            socketChannel.configureBlocking(false);
            socketChannel.register(selector, SelectionKey.OP_READ);
            userName = socketChannel.getLocalAddress().toString().substring(1);
            System.out.println("客户端已准备好");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 客户端发送消息
     *
     * @param message
     */
    public void sendMessage(String message) {
        try {
            message = userName + "说：" + message;
            socketChannel.write(ByteBuffer.wrap(message.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        }
    }

    /**
     * 客户端读取消息
     */
    public void readMessage() {
        try {
            int readChannels = selector.select(5000);
            if (readChannels > 0) {
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    if (key.isReadable()) {
                        SocketChannel channel = (SocketChannel) key.channel();
                        ByteBuffer buf = ByteBuffer.allocate(1024);
                        channel.read(buf);
                        System.out.println("收到来自" + channel.getRemoteAddress() + "的消息：" + new String(buf.array()));
                    } else {
                        System.out.println("在等待。。。。");
                    }
                    iterator.remove();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        ClientChat clientChat = new ClientChat();
        //创建一个线程专门用于读取服务端的数据
        new Thread(() -> {
            while (true) {
                clientChat.readMessage();
            }
        }).start();
        //给服务端发送数据

        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            String next = scanner.next();
            clientChat.sendMessage(next);
        }

    }
}
